package com.example.worker;

import com.example.utils.RabbitUtil;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

/**
 * @author hanjc
 */
public class WorkerB {

    public static void main(String[] args) throws Exception {

        Channel channel = RabbitUtil.getChannel();
        System.out.println("workerB wait for message...");

        //推送的消息如何进行消费的接口回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            RabbitUtil.sleep(1);
            System.out.println("message = " + message);
            // 肯定应答 形参1:消息 2:是否批量应答
            assert channel != null;
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        // 设置不公平分发
        int prefetchCount = 2;
        assert channel != null;
        channel.basicQos(prefetchCount);
        // 启用手动应答
        boolean autoAck = false;
        //取消消费的一个回调接口 如在消费的时候队列被删除掉了
        CancelCallback cancelCallback = (consumerTag) -> System.out.println(consumerTag + " 消费者取消消费 接口回调逻辑");

        /*
          消费者消费消息
          1.消费哪个队列
          2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
          3.消费者成功消费的回调
         */
        channel.basicConsume(RabbitUtil.QUEUE_NAME, autoAck, deliverCallback, cancelCallback);
    }

}